<?php
/* Pi-hole: A black hole for Internet advertisements
*  (c) 2017 Pi-hole, LLC (https://pi-hole.net)
*  Network-wide ad blocking via your own hardware.
*
*  This file is copyright under the latest version of the EUPL.
*  Please see LICENSE file for your rights under this license.
*/

require 'password.php';

if (!$auth) {
    exit('Not authorized');
}

ob_end_flush();
ini_set('output_buffering', '0');
ob_implicit_flush(true);
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

function echoEvent($datatext)
{
    // "pihole -g" command uses an escape sequence to allow overwriting lines = ${OVER}
    // The ${OVER} sequence is a Carriage Return ("\r") followed by "ESC+[+K" ("\e[K")
    // This allows every line (including progress and error messages) to be shown on the page

    // Replace ${OVER} with something we can safely transmit and use on the javascript code
    $datatext = str_replace("\r\e[K", '<------', $datatext);

    // Replace "\r" generated by "pihole-FTL gravity parseList" command
    $datatext = str_replace("\r", '<------', $datatext);

    $pos = strpos($datatext, '<------');
    // If the "<------" string is in the middle of the line we remove everything before it
    // Example: "Pending: String to replace<------Done: String has been replaced"
    // After replacing: "<------Done: String has been replaced"
    if ($pos !== false && $pos !== 0) {
        $datatext = substr($datatext, $pos);
    }
    echo 'data: '.implode("\ndata: ", explode("\n", $datatext))."\n\n";
}

$proc = popen('sudo pihole -g', 'r');
while (!feof($proc)) {
    echoEvent(fread($proc, 4096));
}
